<template>
  <div class="role-management">
    <!-- 角色列表头部 -->
    <div class="mb-4 flex justify-between" v-if="props.roles.length > 0">
      <div class="flex space-x-4">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索角色"
          class="w-64"
        clearable
        @input="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      </div>
      
      <el-button color="#1c1d29" @click="handleAddRole" class="custom-operate-btn">
        创建角色
      </el-button>
    </div>
    
    <!-- 角色列表 -->
    <el-table
      v-if="filteredRoles.length > 0"
      :data="filteredRoles"
      style="width: 100%"
      border
      v-loading="loading"
    >
      <el-table-column prop="actorName" label="角色名" min-width="120" />
      <el-table-column prop="actorAlias" label="角色描述" min-width="150" show-overflow-tooltip />
      
      <el-table-column label="主图" width="110">
        <template #default="{ row }">
          <el-image
            v-if="row.wholeBodyFrontImageUrl"
            :src="row.wholeBodyFrontImageUrl"
            fit="cover"
            class="role-image"
            @click="previewImage(row.wholeBodyFrontImageUrl)"
          />
          <el-tag v-else type="info" size="small">未上传</el-tag>
        </template>
      </el-table-column>
      
      <el-table-column label="侧图" width="110">
        <template #default="{ row }">
          <el-image
            v-if="row.wholeBodySideImageUrl"
            :src="row.wholeBodySideImageUrl"
            fit="cover"
            class="role-image"
            @click="previewImage(row.wholeBodySideImageUrl)"
          />
          <el-tag v-else type="info" size="small">未上传</el-tag>
        </template>
      </el-table-column>
      
      <el-table-column label="背图" width="110">
        <template #default="{ row }">
          <el-image
            v-if="row.wholeBodyBackImageUrl"
            :src="row.wholeBodyBackImageUrl"
            fit="cover"
            class="role-image"
            @click="previewImage(row.wholeBodyBackImageUrl)"
          />
          <el-tag v-else type="info" size="small">未上传</el-tag>
        </template>
      </el-table-column>
      
      <el-table-column label="半身图" width="110">
        <template #default="{ row }">
          <el-image
            v-if="row.halfBodyImageUrl"
            :src="row.halfBodyImageUrl"
            fit="cover"
            class="role-image"
            @click="previewImage(row.halfBodyImageUrl)"
          />
          <el-tag v-else type="info" size="small">未上传</el-tag>
        </template>
      </el-table-column>
      
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <span class="txt-btn mr-2" @click="handleEditRole(row)">编辑</span>
          <span class="txt-btn" @click="handleDeleteRole(row)">删除</span>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 搜索结果为空的状态 -->
    <div v-if="isEmptySearchResult" class="empty-search-state">
      <img src="@/assets/images/empty.png" class="empty-image" alt="无搜索结果" />
      <p class="empty-text">没有符合条件的角色</p>
    </div>
    
    <!-- 完全没有角色的状态 -->
    <div v-if="!loading && props.roles.length === 0" class="empty-state">
      <img src="@/assets/images/empty.png" class="empty-image" alt="暂无角色" />
      <p class="empty-text">暂无角色，快点击按钮创建吧</p>
      <el-button color="#1c1d29" @click="handleAddRole">创建角色</el-button>
    </div>
    
    <!-- 角色弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑角色' : '创建角色'"
      width="680px"
      :close-on-click-modal="false"
      :before-close="handleDialogClose"
      destroy-on-close
      custom-class="role-dialog"
    >
      <template #header>
        <div class="dialog-title">{{ isEdit ? '编辑角色' : '创建角色' }}</div>
      </template>
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleRules"
        label-position="top"
      >
        <el-form-item>
          <template #label>
            <span class="form-label">角色名称<span class="required-mark">*</span></span>
          </template>
          <el-input v-model="roleForm.actorName" placeholder="请输入角色名称" maxlength="50" show-word-limit />
            </el-form-item>
        
        <el-form-item>
          <template #label>
            <span class="form-label">角色描述</span>
          </template>
          <el-input 
            v-model="roleForm.actorAlias" 
            type="textarea" 
            :rows="3"
            placeholder="请输入角色描述" 
            maxlength="200" 
            show-word-limit
          />
            </el-form-item>
        
        <!-- 主图 -->
        <el-form-item>
          <template #label>
            <span class="form-label">主图<span class="required-mark">*</span></span>
          </template>
          <div class="image-upload-container">
              <PicUpload @start="beforeImageUpload" @finish="(fileKey) => handleImageUpload(fileKey, 'wholeBodyFrontImageUrl')" :defaultUrl="roleForm.wholeBodyFrontImageUrl" />
          </div>
            </el-form-item>
        
        <!-- 侧图 -->
        <el-form-item>
          <template #label>
            <span class="form-label">侧图<span class="required-mark">*</span></span>
          </template>
          <div class="image-upload-container">
            <PicUpload @start="beforeImageUpload" @finish="(fileKey) => handleImageUpload(fileKey, 'wholeBodySideImageUrl')" :defaultUrl="roleForm.wholeBodySideImageUrl" />
          </div>
            </el-form-item>
        
        <!-- 背图 -->
        <el-form-item>
          <template #label>
            <span class="form-label">背图<span class="required-mark">*</span></span>
          </template>
          <div class="image-upload-container">
            <PicUpload @start="beforeImageUpload" @finish="(fileKey) => handleImageUpload(fileKey, 'wholeBodyBackImageUrl')" :defaultUrl="roleForm.wholeBodyBackImageUrl" />
          </div>
            </el-form-item>
        
        <!-- 半身图 -->
        <el-form-item>
          <template #label>
            <span class="form-label">半身图<span class="required-mark">*</span></span>
          </template>
          <div class="image-upload-container">
            <PicUpload @start="beforeImageUpload" @finish="(fileKey) => handleImageUpload(fileKey, 'halfBodyImageUrl')" :defaultUrl="roleForm.halfBodyImageUrl" />
          </div>
            </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button class="save-el-button" @click="handleDialogClose">取消</el-button>
          <el-button class="save-el-button" color="#1c1d29" @click="handleSaveRole" :loading="saveLoading">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 图片预览 -->
    <ImagePreview 
      v-model:visible="previewVisible" 
      :image-url="previewImageUrl" 
    />
  </div>
</template>

<script setup>
import { ref, computed, reactive, nextTick, watch } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { Search, Plus, Edit, Delete, CopyDocument, Close } from '@element-plus/icons-vue'
import { debounce } from 'lodash-es'
import { createActor, updateActor, uploadFile, deleteActor, getDramaActor } from '@/api/drama'
import PicUpload from '@/components/common/PicUpload.vue'
import ImagePreview from '@/components/common/ImagePreview.vue'

const props = defineProps({
  roles: {
    type: Array,
    default: () => []
  },
  disabled: {
    type: Boolean,
    default: false
  },
  dramaId: {
    type: [String, Number],
    default: ''
  }
})

const emit = defineEmits(['update:roles'])

// 角色列表
const loading = ref(false)
const searchKeyword = ref('')
const hasRoles = ref(false) // 添加一个变量来跟踪是否有角色数据

// 搜索处理
const handleSearch = debounce(() => {
  // 搜索逻辑在计算属性中实现
}, 300)

// 过滤后的角色列表
const filteredRoles = computed(() => {
  if (!searchKeyword.value) return props.roles
  
  const keyword = searchKeyword.value.toLowerCase()
  return props.roles.filter(role => 
    role.actorName.toLowerCase().includes(keyword) || 
    (role.actorAlias && role.actorAlias.toLowerCase().includes(keyword))
  )
})

// 计算是否为搜索结果为空的状态
const isEmptySearchResult = computed(() => {
  return searchKeyword.value && props.roles.length > 0 && filteredRoles.value.length === 0
})

// 图片预览
const previewVisible = ref(false)
const previewImageUrl = ref('')

const previewImage = (url) => {
  previewImageUrl.value = url
  previewVisible.value = true
}

// 角色表单
const dialogVisible = ref(false)
const isEdit = ref(false)
const editIndex = ref(-1)
const saveLoading = ref(false)
const roleFormRef = ref(null)

const roleForm = reactive({
  actorName: '',
  actorAlias: '',
  wholeBodyFrontImageUrl: '',
  wholeBodySideImageUrl: '',
  wholeBodyBackImageUrl: '',
  halfBodyImageUrl: '',
  actorId: null,
  // 新增图片资源key字段
  wholeBodyFrontResKey: '',
  wholeBodySideResKey: '',
  wholeBodyBackResKey: '',
  halfBodyResKey: ''
})

// 表单验证规则
const roleRules = {
  actorName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' }
  ],
  wholeBodyFrontImageUrl: [
    { required: true, message: '请上传主图', trigger: 'change' }
  ],
  wholeBodySideImageUrl: [
    { required: true, message: '请上传侧图', trigger: 'change' }
  ],
  wholeBodyBackImageUrl: [
    { required: true, message: '请上传背图', trigger: 'change' }
  ],
  halfBodyImageUrl: [
    { required: true, message: '请上传半身图', trigger: 'change' }
  ]
}

// 创建角色
const handleAddRole = () => {
  isEdit.value = false
  editIndex.value = -1
  
  // 重置表单
  roleForm.actorName = ''
  roleForm.actorAlias = ''
  roleForm.wholeBodyFrontImageUrl = ''
  roleForm.wholeBodySideImageUrl = ''
  roleForm.wholeBodyBackImageUrl = ''
  roleForm.halfBodyImageUrl = ''
  roleForm.actorId = null
  roleForm.wholeBodyFrontResKey = ''
  roleForm.wholeBodySideResKey = ''
  roleForm.wholeBodyBackResKey = ''
  roleForm.halfBodyResKey = ''
  
  dialogVisible.value = true
  
  // 重置表单校验
  nextTick(() => {
    roleFormRef.value && roleFormRef.value.resetFields()
  })
}

// 编辑角色
const handleEditRole = (row) => {
  isEdit.value = true
  // 重置表单
  Object.keys(roleForm).forEach(key => {
    roleForm[key] = ''
  })
  editIndex.value = props.roles.findIndex(item => item.id === row.id)
  
  // 填充表单
  roleForm.actorName = row.actorName || ''
  roleForm.actorAlias = row.actorAlias || ''
  roleForm.wholeBodyFrontImageUrl = row.wholeBodyFrontImageUrl || ''
  roleForm.wholeBodySideImageUrl = row.wholeBodySideImageUrl || ''
  roleForm.wholeBodyBackImageUrl = row.wholeBodyBackImageUrl || ''
  roleForm.halfBodyImageUrl = row.halfBodyImageUrl || ''
  
  // 设置ResKey字段
  roleForm.wholeBodyFrontResKey = row.wholeBodyFrontResKey || ''
  roleForm.wholeBodySideResKey = row.wholeBodySideResKey || ''
  roleForm.wholeBodyBackResKey = row.wholeBodyBackResKey || ''
  roleForm.halfBodyResKey = row.halfBodyResKey || ''
  
  // 确保actorId被正确设置
  roleForm.actorId = row.actorId || row.id
  
  dialogVisible.value = true
  
  // 重置表单校验
  nextTick(() => {
    roleFormRef.value && roleFormRef.value.resetFields()
  })
}

// 复制角色
const handleCopyRole = (row) => {
  const newRole = JSON.parse(JSON.stringify(row))
  newRole.id = Date.now() // 生成新ID
  newRole.actorId = null  // 清除actorId，确保被视为新角色
  newRole.actorName = `${newRole.actorName} (副本)`
  
  const updatedRoles = [...props.roles, newRole]
  emit('update:roles', updatedRoles)
  
  ElMessage.success('角色复制成功')
}

// 关闭弹窗
const handleDialogClose = () => {
  dialogVisible.value = false
  // 重置表单校验
  nextTick(() => {
    roleFormRef.value && roleFormRef.value.resetFields()
  })
}

// 删除角色
const handleDeleteRole = (row) => {
  ElMessageBox.confirm(`确定要删除角色 "${row.actorName}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: '',
    closeIcon: 'add',
    customClass: 'delete-confirm-dialog',
    confirmButtonClass: 'confirm-delete-btn-class',
    cancelButtonClass: 'cancel-delete-btn-class'
  }).then(async () => {
    try {
      // 如果有actorId则调用API删除
      if (row.actorId && props.dramaId) {
        await deleteActor(row.actorId)
        ElMessage.success('角色删除成功')
        
        // 重新获取角色列表
        refreshRoleList()
      } else {
        // 如果没有actorId，仅在本地删除
    const updatedRoles = props.roles.filter(item => item.id !== row.id)
    emit('update:roles', updatedRoles)
    ElMessage.success('角色删除成功')
      }
    } catch (error) {
      console.error('删除角色失败:', error)
      ElMessage.error('删除角色失败，请重试')
    }
  }).catch(() => {})
}

// 刷新角色列表
const refreshRoleList = async () => {
  if (!props.dramaId) return
  
  loading.value = true
  try {
    const { data } = await getDramaActor(props.dramaId)
    emit('update:roles', data || [])
    hasRoles.value = (data && data.length > 0) // 更新hasRoles状态
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}

// 监听props.roles变化
watch(() => props.roles, (newRoles) => {
  hasRoles.value = newRoles && newRoles.length > 0
}, { immediate: true })

// 上传前验证
const beforeImageUpload = (file) => {
  saveLoading.value = true
}

// 处理图片上传
const handleImageUpload = async (fileKey, field) => {
  try {
    if (fileKey) {
      // 根据不同字段设置对应的ResKey
      switch (field) {
        case 'wholeBodyFrontImageUrl':
          roleForm.wholeBodyFrontResKey = fileKey
          break
        case 'wholeBodySideImageUrl':
          roleForm.wholeBodySideResKey = fileKey
          break
        case 'wholeBodyBackImageUrl':
          roleForm.wholeBodyBackResKey = fileKey
          break
        case 'halfBodyImageUrl':
          roleForm.halfBodyResKey = fileKey
          break
      }
    }
    saveLoading.value = false
  } catch (error) {
    saveLoading.value = false
  }
}

// 保存角色
const handleSaveRole = async () => {
  // 表单验证
  try {
    await roleFormRef.value.validate()
  } catch (error) {
    return
  }
  
  // 验证是否所有图片都已上传并获取了ResKey
  if (!roleForm.wholeBodyFrontResKey && !roleForm.wholeBodyFrontImageUrl) {
    ElMessage.warning('请上传主图')
    return
  }
  
  if (!roleForm.wholeBodySideResKey && !roleForm.wholeBodySideImageUrl) {
    ElMessage.warning('请上传侧图')
    return
  }
  
  if (!roleForm.wholeBodyBackResKey && !roleForm.wholeBodyBackImageUrl) {
    ElMessage.warning('请上传背图')
    return
  }
  
  if (!roleForm.halfBodyResKey && !roleForm.halfBodyImageUrl) {
    ElMessage.warning('请上传半身图')
    return  
  }
  
  saveLoading.value = true
  
  try {
    const roleData = {
      actorName: roleForm.actorName,
      actorAlias: roleForm.actorAlias || '',
      actorDescription: roleForm.actorAlias || '',
      dramaId: props.dramaId,
      wholeBodyFrontResKey: roleForm.wholeBodyFrontResKey,
      wholeBodySideResKey: roleForm.wholeBodySideResKey,
      wholeBodyBackResKey: roleForm.wholeBodyBackResKey,
      halfBodyResKey: roleForm.halfBodyResKey
    }
    
    // 如果是编辑模式，添加actorId
    if (isEdit.value && roleForm.actorId) {
      roleData.actorId = roleForm.actorId
    }
    
    // 如果有dramaId，调用API创建或更新角色
    if (props.dramaId) {
      let response;
      
      // 根据是否为编辑模式，调用不同的API
      if (isEdit.value) {
        // 编辑模式，调用更新API
        response = await updateActor(roleData)
      } else {
        // 新增模式，调用创建API
        response = await createActor(roleData)
      }
      
      // 如果API调用成功，更新本地数据
      if (response.data) {
        const localRoleData = {
          id: response.data.id || Date.now(),
          actorId: response.data.actorId || response.data.id,
          actorName: roleForm.actorName,
          actorAlias: roleForm.actorAlias || '',
          wholeBodyFrontImageUrl: roleForm.wholeBodyFrontImageUrl,
          wholeBodySideImageUrl: roleForm.wholeBodySideImageUrl,
          wholeBodyBackImageUrl: roleForm.wholeBodyBackImageUrl,
          halfBodyImageUrl: roleForm.halfBodyImageUrl,
          wholeBodyFrontResKey: roleForm.wholeBodyFrontResKey,
          wholeBodySideResKey: roleForm.wholeBodySideResKey,
          wholeBodyBackResKey: roleForm.wholeBodyBackResKey,
          halfBodyResKey: roleForm.halfBodyResKey
        }
        
        let updatedRoles = []
        
        if (isEdit.value && editIndex.value !== -1) {
          // 编辑模式
          updatedRoles = [...props.roles]
          updatedRoles[editIndex.value] = localRoleData
        } else {
          // 新增模式
          updatedRoles = [...props.roles, localRoleData]
        }
        console.log(updatedRoles)
        emit('update:roles', updatedRoles)
        
        ElMessage.success(isEdit.value ? '角色更新成功' : '角色添加成功')
        dialogVisible.value = false
      }
    } else {
      // 如果没有dramaId，只更新本地数据
      const localRoleData = {
        id: isEdit.value ? props.roles[editIndex.value].id : Date.now(),
        actorId: roleForm.actorId,
        actorName: roleForm.actorName,
        actorAlias: roleForm.actorAlias || '',
        wholeBodyFrontImageUrl: roleForm.wholeBodyFrontImageUrl,
        wholeBodySideImageUrl: roleForm.wholeBodySideImageUrl,
        wholeBodyBackImageUrl: roleForm.wholeBodyBackImageUrl,
        halfBodyImageUrl: roleForm.halfBodyImageUrl,
        wholeBodyFrontResKey: roleForm.wholeBodyFrontResKey,
        wholeBodySideResKey: roleForm.wholeBodySideResKey,
        wholeBodyBackResKey: roleForm.wholeBodyBackResKey,
        halfBodyResKey: roleForm.halfBodyResKey
      }
      
      let updatedRoles = []
      
      if (isEdit.value && editIndex.value !== -1) {
        // 编辑模式
        updatedRoles = [...props.roles]
        updatedRoles[editIndex.value] = localRoleData
      } else {
        // 新增模式
        updatedRoles = [...props.roles, localRoleData]
      }
      
      emit('update:roles', updatedRoles)
      
      ElMessage.success(isEdit.value ? '角色更新成功' : '角色添加成功')
      dialogVisible.value = false
    }
  } catch (error) {
    console.error('保存角色失败:', error)
    ElMessage.error('保存失败，请重试')
  } finally {
    saveLoading.value = false
  }
}
</script>

<style scoped>
:deep(.el-upload.el-upload--text) {
  width: 100%;
}
:deep(.el-image__inner) {
  border-radius: 4px !important;
}
.role-image {
  width: 60px;
  aspect-ratio: 9 / 16;
  border-radius: 4px;
  object-fit: cover;
  cursor: pointer;
  padding: 4px;
  overflow: hidden;
}

.image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
  width: 100px;
  height: 100px;
}

.image-placeholder,
.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100px;
  width: 100px;
  color: #8c939d;
  background: #fff;
}

.uploaded-image {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}

.upload-icon {
  font-size: 24px;
}

.upload-text {
  color: #525466;
  font-size: 14px;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 186px;
}

/* 搜索结果为空的状态样式 */
.empty-search-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 80px;
}

.empty-image {
  width: 240px;
  height: 240px;
}

.empty-text {
  font-size: 14px;
  color: #787C8F;
  margin: 20px 0;
}

/* 表单样式 */
.form-label {
  font-weight: normal;
  font-size: 14px;
  font-weight: 500;
  color: var(--theme-color, #1C1D29);
}

.required-mark {
  color: #f56c6c;
  margin-left: 4px;
}

.image-upload-container {
  width: 100%;
}

:deep(.el-upload-dragger) {
  width: 100%;
  background-color: transparent;
  border: none;
  padding: 0;
}

/* 对话框样式 */
.dialog-title {
  font-size: 16px;
  font-weight: 500;
  color: #1C1D29;
  line-height: 16px;
}

:deep(.role-dialog .el-dialog__header) {
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
  margin-right: 0;
}

:deep(.el-button--primary) {
  background-color: var(--theme-color, #1C1D29);
  border-color: var(--theme-color, #1C1D29);
}

:deep(.el-button--primary:hover) {
  background-color: var(--primary-hover-color, #2d2e3d);
  border-color: var(--primary-hover-color, #2d2e3d);
}

:deep(.el-button--primary:disabled) {
  background-color: var(--primary-disabled-color, #A2A6B8);
  border-color: var(--primary-disabled-color, #A2A6B8);
}

/* Image preview styles have been moved to the ImagePreview component */
</style> 